﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Net;
using System.IO;
using System.Web;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;

namespace SecureRemoteControlServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            // 更新应用程序设置，以确保顺利过渡到新版本的应用程序
            if (!Properties.Settings.Default.Upgraded)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.Upgraded = true;
                Properties.Settings.Default.Save();
            }

            InitializeComponent();

            var timer = new System.Windows.Threading.DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 10);
            timer.Tick += (sender, e) => ButtonSend_Click(sender, null);
            timer.Start();
            var timer2 = new System.Windows.Threading.DispatcherTimer();
            timer2.Interval = new TimeSpan(0, 1, 0);
            timer2.Tick += (sender, e) => ButtonUpdate_Click(sender, null);
            timer2.Start();

            Bemfa.ReceiveCallback receive = buffer => {
                if (buffer.Contains("off"))
                    this.ButtonShutdown_Click(null, null);
            };
            new Thread(new Bemfa().Connect) { IsBackground = true }.Start(receive);

            TextBoxAddress.Text = Properties.Settings.Default.ServerAddress;
            TextBoxID.Text = Properties.Settings.Default.ClientID;
            TextBoxDynv6Zone.Text = Properties.Settings.Default.Dynv6Zone;
            TextBoxDynv6Token.Text = Properties.Settings.Default.Dynv6Token;
            TextBoxBemfaUid.Text = Properties.Settings.Default.BemfaUid;
            TextBoxBemfaTopic.Text = Properties.Settings.Default.BemfaTopic;
            if (TextBoxID.Text == "")
            {
                TextBoxID.Text = System.Net.Dns.GetHostName();
            }
        }

        string preText;
        string preDateTime;
        int preCount = 0;
        void Log(string text)
        {
            if (text == preText)
            {
                TextBoxLog.Text = TextBoxLog.Text.Remove(TextBoxLog.Text.LastIndexOf(Environment.NewLine));
                TextBoxLog.Text += Environment.NewLine + preDateTime + "-" + DateTime.Now.ToString() + "(" + (++preCount) + ") " + text;
            }
            else
            {
                preDateTime = DateTime.Now.ToString();
                preCount = 1;
                TextBoxLog.Text += Environment.NewLine + preDateTime + " " + text;
            }
            preText = text;
            TextBoxLog.ScrollToEnd();
        }

        void Send(string requestUriString)
        {
            WebRequest request = WebRequest.Create(requestUriString);
            request.Credentials = CredentialCache.DefaultCredentials;
            WebResponse response = request.GetResponse();
            response.Close();
        }

        private void ButtonSend_Click(object sender, RoutedEventArgs e)
        {
            // 生成数据
            TextBoxInfo.Text = string.Join("\n", Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(address => !address.IsIPv6LinkLocal).Select(address => address.ToString()));
            var requestUriString = TextBoxAddress.Text + "?id=" + TextBoxID.Text + "&send=" + HttpUtility.UrlEncode(TextBoxInfo.Text);

            // 解决异常问题
            ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;

            // Create a request for the URL.
            WebRequest request = WebRequest.Create(requestUriString);

            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;

            //request.Method = WebRequestMethods.Http.Get;

            // Get the response.
            using (WebResponse response = request.GetResponse())
            {
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);

                // Get the stream containing content returned by the server.
                // The using block ensures the stream is automatically closed.
                using (Stream dataStream = response.GetResponseStream())
                {
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();
                    // Display the content.
                    Console.WriteLine(responseFromServer);

                    // 处理数据
                    switch (responseFromServer)
                    {
                        case "1":
                            Send(requestUriString + "&back");
                            ButtonShutdown_Click(null, null);
                            break;
                        case "2":
                            Send(requestUriString + "&back");
                            ButtonReboot_Click(null, null);
                            break;
                        default:
                            Log("发送完成！");
                            break;
                    };
                }

                // Close the response.
                response.Close();
            }
        }

        private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
        {
            // 生成数据
            var IPv6Address = Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 && !address.IsIPv6LinkLocal).ToString();
            var requestUriString = @"https://dynv6.com/api/update" + "?zone=" + TextBoxDynv6Zone.Text + "&token=" + TextBoxDynv6Token.Text + "&ipv6=" + IPv6Address;

            // 解决异常问题
            ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;

            // Create a request for the URL.
            WebRequest request = WebRequest.Create(requestUriString);

            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;

            //request.Method = WebRequestMethods.Http.Get;

            // Get the response.
            using (WebResponse response = request.GetResponse())
            {
                // Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);

                // Get the stream containing content returned by the server.
                // The using block ensures the stream is automatically closed.
                using (Stream dataStream = response.GetResponseStream())
                {
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();
                    // Display the content.
                    Console.WriteLine(responseFromServer);

                    // TODO: 错误处理
                    Log("发送完成！");
                }

                // Close the response.
                response.Close();
            }
        }

        private void ButtonSleep_Click(object sender, RoutedEventArgs e)
        {
        }

        private void ButtonShutdown_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("shutdown.exe", " -s");
            Log("关闭计算机完成！");
        }

        private void ButtonReboot_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("shutdown.exe", " -r");
            Log("重启计算机完成！");
        }

        private void ButtonExit_Click(object sender, RoutedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void TextBoxAddress_TextChanged(object sender, TextChangedEventArgs e)
        {
            Properties.Settings.Default.ServerAddress = TextBoxAddress.Text;
            Properties.Settings.Default.Save();
        }

        private void TextBoxID_TextChanged(object sender, TextChangedEventArgs e)
        {
            Properties.Settings.Default.ClientID = TextBoxID.Text;
            Properties.Settings.Default.Save();
            if (TextBoxID.Text == "")
            {
                TextBoxID.Text = System.Net.Dns.GetHostName();
            }
        }

        private void TextBoxDynv6Zone_TextChanged(object sender, TextChangedEventArgs e)
        {
            Properties.Settings.Default.Dynv6Zone = TextBoxDynv6Zone.Text;
            Properties.Settings.Default.Save();
        }

        private void TextBoxDynv6Token_TextChanged(object sender, TextChangedEventArgs e)
        {
            Properties.Settings.Default.Dynv6Token = TextBoxDynv6Token.Text;
            Properties.Settings.Default.Save();
        }

        private void TextBoxBemfaUid_TextChanged(object sender, TextChangedEventArgs e)
        {
            Properties.Settings.Default.BemfaUid = TextBoxBemfaUid.Text;
            Properties.Settings.Default.Save();
        }

        private void TextBoxBemfaTopic_TextChanged(object sender, TextChangedEventArgs e)
        {
            Properties.Settings.Default.BemfaTopic = TextBoxBemfaTopic.Text;
            Properties.Settings.Default.Save();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
#if DEBUG
            this.Title += " [Debug Mode]";
#endif
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            new Help() { Owner = this }.Show(0);
        }

        private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e)
        {
            new Help() { Owner = this }.Show(1);
        }
    }
}
